/**
 * Copyright (C) 2010, 2011 Neofonie GmbH
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package eu.dicodeproject.analysis.lucene;

import org.apache.commons.lang.NotImplementedException;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;

import java.io.IOException;
import java.io.StringReader;
import java.util.Iterator;

/**
 * Wraps an analyzer in an iterable for strings.
 */
public class IterableAnalyzer implements Iterable<String>, Iterator<String> {

  private String buffer;
  private TokenStream tokenStream;
  private CharTermAttribute charTermAttribute;

  public IterableAnalyzer(Analyzer analyzer, String text) throws IOException {
    StringReader textReader = new StringReader(text);
    tokenStream = analyzer.tokenStream(null, textReader);
    charTermAttribute = tokenStream.getAttribute(CharTermAttribute.class);
    updateBuffer();
  }

  /**
   * Sets the next token to the string buffer.
   * Sets the buffer to null if the token stream does not contain any more tokens.
   * @throws IOException inherited from TokenStream.incrementToken.
   */
  private void updateBuffer() throws IOException {
    if (tokenStream.incrementToken()) {
      buffer = charTermAttribute.toString();
    }
    else {
      buffer = null;
    }
  }

  @Override
  public boolean hasNext() {
    return buffer != null;
  }

  @Override
  public String next() {
    String oldBuffer = buffer;
    try {
      updateBuffer();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return oldBuffer;
  }

  @Override
  public void remove() {
    throw new NotImplementedException();
  }

  @Override
  public Iterator<String> iterator() {
    return this;
  }
}